#include <stdio.h>
#include "driver/i2c.h"
#include "HAL.h"
#include "string.h"

static const char *TAG = "RTC-SD2506AP";

#define I2C_MASTER_SCL_IO           20      /*!< GPIO number used for I2C master clock */
#define I2C_MASTER_SDA_IO           19      /*!< GPIO number used for I2C master data  */
#define I2C_MASTER_NUM              0                          /*!< I2C master i2c port number, the number of i2c peripheral interfaces available will depend on the chip */
#define I2C_MASTER_FREQ_HZ          400000                     /*!< I2C master clock frequency */
#define I2C_MASTER_TX_BUF_DISABLE   0                          /*!< I2C master doesn't need buffer */
#define I2C_MASTER_RX_BUF_DISABLE   0                          /*!< I2C master doesn't need buffer */
#define I2C_MASTER_TIMEOUT_MS       1000

/******************** RTC Device address ********************/
#define SD2506AP_SENSOR_ADDR                0x32

/******************** Control register ********************/
#define		CTR1					0x0F
#define		CTR2					0x10
#define		CTR3					0x11

/******************** Battery register ********************/
#define		CHARGE_MG			0x18		//充电管理寄存器地址
#define		Bat_bit8			0x1A		//电量最高位寄存器地址
#define		Bat_Low8			0x1B		//电量低八位寄存器地址

// 测试
RTC_TIME  RTC={0x55,0x47,0x17,0x07,0x28,0x04,0x24};	//初始化时间结构体变量（设置时间：2016年1月26日 14:59:55  星期二）
//           55秒 47分 17时 周日 28日 4月 24年

static esp_err_t i2c_master_init(void)
{
    int i2c_master_port = I2C_MASTER_NUM;

    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = I2C_MASTER_SDA_IO,
        .scl_io_num = I2C_MASTER_SCL_IO,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = I2C_MASTER_FREQ_HZ,
    };

    i2c_param_config(i2c_master_port, &conf);

    return i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
}

static esp_err_t RTC_reg_read(uint8_t reg_addr, uint8_t *data, size_t len)
{
    return i2c_master_write_read_device(I2C_MASTER_NUM, SD2506AP_SENSOR_ADDR, &reg_addr, 1, data, len, I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS);
}

static esp_err_t RTC_reg_write_byte(uint8_t reg_addr, uint8_t data)
{
    int ret;
    uint8_t write_buf[2] = {reg_addr, data};

    ret = i2c_master_write_to_device(I2C_MASTER_NUM, SD2506AP_SENSOR_ADDR, write_buf, sizeof(write_buf), I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS);

    return ret;
}

static esp_err_t RTC_reg_write(uint8_t reg_addr, const uint8_t* data,uint8_t data_len)
{
    int ret;
    uint8_t write_buf[128] = {0};
    write_buf[0] = reg_addr;
    memcpy(write_buf+1,data,data_len);
    ret = i2c_master_write_to_device(I2C_MASTER_NUM, SD2506AP_SENSOR_ADDR, write_buf, 1+data_len, I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS);

    return ret;
}



void RTC_Write_Enable()
{
    // 写允许
    RTC_reg_write_byte(CTR2,0x80);
    RTC_reg_write_byte(CTR1,0x84);
}

void RTC_Write_Disable()
{
    // 写禁止
    RTC_reg_write_byte(CTR1,0x00);
    RTC_reg_write_byte(CTR2,0x00);
}

void RTC_set_data(const RTC_TIME time)
{
    RTC_Write_Enable();
    RTC_reg_write(0x00,&time,sizeof(time));
    RTC_Write_Disable();
}

void RTC_read_data(RTC_TIME* time)
{
    // 小端
    RTC_TIME data;
    RTC_reg_read(0x00,&data,sizeof(data));

    // 解析
    time->hour = (data.hour>>4)*10 + (data.hour&0x0f);
    time->minute = (data.minute>>4)*10 + (data.minute&0x0f);
    time->second = (data.second>>4)*10 + (data.second&0x0f);
    time->year = (data.year>>4)*10 + (data.year&0x0f);
    time->month = (data.month>>4)*10 + (data.month&0x0f);
    time->day = (data.day>>4)*10 + (data.day&0x0f);
}

void RTC_Init()
{
    i2c_master_init();

    // RTC_set_data(RTC);  //设置时间演示

    RTC_Write_Enable();

    //如果有内置可充电电池，需要在上电时初始化充电功能
    RTC_reg_write_byte(CHARGE_MG,0x82);

    RTC_Write_Disable();


    RTC_TIME TIME_1;
    RTC_read_data(&TIME_1);
    ESP_LOGI(TAG, "20%d/%d/%d %d:%d:%d\n",TIME_1.year,TIME_1.month,TIME_1.day,\
                                            TIME_1.hour,TIME_1.minute,TIME_1.second);

}